import React, { Component } from "react";
import { connect } from "dva/index";
import { Icon, Button, Input, Form, message, Pagination } from "antd";
import styles from "./index.less";
import { knowledgeDialogSlots, knowledgeDialogNodeInfo } from '@/services/dialog';
import UserSession from "@/UserSession";
import knowledgeHome from "@/services/knowledgeHome";
const FormItem = Form.Item;

@connect(({ collectSlot, loading }) => ({
	collectSlot,
	loading: loading.effects["collectSlot/fetchSlot"],
}))
class DialogStart extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			addValue: "",
			questions: [],
			slots: [],
			questionIndex: -1,
			nodeId: props.nodeId,
			stage: props.stage,
			dialogId: props.dialogId, // 多轮对话id
			stageId: "",
			page: 1,
			minIndex: 0,
			maxIndex: 10,
			standardQuestion: "",
		};
	}

	componentDidMount() {
		this.getInit();
		this.getDialogSlots();
		message.config({
			getContainer: () => document.getElementById("rightDrawer"),
		});
	}

	getInit = async () => {
		const { dispatch, dialogId, nodeId, stage } = this.props;
		if (UserSession.isSystemKnowledge()) { 
			let res = await knowledgeDialogNodeInfo({
				nodeType: "start",
				dialogId: dialogId,
				nodeId: nodeId,
				field: "",
			});
			const questions = !res.dialogStage.data.questions
				? []
				: res.dialogStage.data.questions;
			const standardQuestion = questions[0] ? questions[0] : "";
			questions.shift();
			this.setState({
				stageId: res.dialogStage.id,
				questions: questions,
				standardQuestion,
			});
		} else {
			dispatch({
				type: "collectSlot/fetchSlot",
				payload: {
					stage: "start",
					dialogId: dialogId,
					nodeId: nodeId,
					field: "",
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					const questions = !res.dialogStage.data.questions
						? []
						: res.dialogStage.data.questions;
					const standardQuestion = questions[0] ? questions[0] : "";
					questions.shift();
					this.setState({
						stageId: res.dialogStage.id,
						questions: questions,
						standardQuestion,
					});
				},
			});
		}
		
	};

	getDialogSlots = async () => {
		const { dialogId } = this.state;
		const { dispatch } = this.props;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeDialogSlots({ dialogId })
			this.setState({
			  slots: res==null?[]:res,
			})
		  } else {
			dispatch({
				type: "dialogCommon/getDialogSlots",
				payload: {
					dialogId: dialogId,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					this.setState({
						slots: res,
					});
				},
			});
		}
	};

	addValue = () => {
		const { questions, addValue } = this.state;
		switch (addValue.trim()) {
			case "":
				break;
			default:
				questions.push(addValue);
				knowledgeHome.postDialogSimilarAdd();
				this.setState({
					questions: questions,
					addValue: "",
				});
		}
	};

	onChange = (e, type, index) => {
		switch (type) {
			case "a":
				this.setState({
					addValue: e.target.value,
				});
				break;
			case "b":
				const { questions } = this.state;
				questions[index] = e.target.value;
				this.setState({
					questions: questions,
				});
				break;
		}
	};

	changeQuestions = (q, i, type) => {
		let { questions, page, minIndex, maxIndex } = this.state;
		switch (type) {
			case "del":
				questions.splice(i, 1);
				const questionPages = questions.filter(
					(item, i) => (i > minIndex || i === minIndex) && i < maxIndex
				);
				if (questionPages.length === 0 && page != 1) {
					page -= 1;
				};
				knowledgeHome.postDialogSimilarDel()
				this.setState(
					{
						questions: questions,
						page,
					},
					() => {
						this.onChangeQuestionPage(page);
					}
				);
				break;
			case "up":
				questions.splice(i, 1);
				questions.unshift(q);
				this.setState({
					questions: questions,
				});
				break;
		}
	};

	changeQuestionsIndex = (i) => {
		this.setState({
			questionIndex: i,
		});
	};

	addSlots = (name, index) => {
		const { addValue, questions } = this.state;
		if (index === -1) {
			const newValue = addValue + "<" + name + ">";
			this.setState({
				addValue: newValue,
			});
		} else {
			const newValue = questions[index] + "<" + name + ">";
			questions[index] = newValue;
			this.setState({
				questions: questions,
			});
		}

		const resemblanceX = `resemblance${index}`;
		this.refs[resemblanceX].focus();
	};

	save = () => {
		const { questions, stageId, addValue, standardQuestion } = this.state;
		const { dispatch, stage } = this.props;
		if (!standardQuestion) {
			message.error("请输入标准问");
			return false;
		}
		if (addValue) {
			questions.push(addValue);
		}
		// if(questions.length < 0 || questions.length === 0 ){
		//   message.info("请至少填写一条相似问");
		//   return false
		// }

		let questionData = [...questions];
		questionData.unshift(standardQuestion);
		dispatch({
			type: "dialogStart/saveStage",
			payload: {
				id: stageId,
				field: "data",
				data: {
					autoEnter: true,
					questions: questionData,
				},
				stage,
			},
			callback: (res) => {
				message.info(res.msg);
				this.props.closeDrawer();
			},
		});
	};

	/**
	 * 问题分页
	 * @returns {*}
	 */
	onChangeQuestionPage = (page) => {
		const minIndex = (page - 1) * 10;
		const maxIndex = (page - 1) * 10 + 10;
		console.log(minIndex, maxIndex);
		this.setState({
			minIndex,
			maxIndex,
			page,
		});
	};

	/**
	 * 标准问input修改
	 * @returns {*}
	 */
	onChangeStandard = (e) => {
		this.setState({
			standardQuestion: e.target.value,
		});
	};

	/**
	 * 标准问添加词槽
	 * @returns {*}
	 */
	addSlotsToStandard = (name) => {
		const { standardQuestion } = this.state;
		const newStandard = standardQuestion + "<" + name + ">";
		this.setState({
			standardQuestion: newStandard,
		});
	};

	render() {
		const {
			questions,
			slots,
			page,
			minIndex,
			maxIndex,
			standardQuestion,
		} = this.state;
		return (
			<div>
				<Icon style={{ transform: "rotate(90deg)" }} type='minus' />
				自定义触发相似问
				<div style={{ padding: "15px 0px 15px 10px", width: "100%" }}>
					<label>
						<span style={{ color: "red" }}>*</span>标准问：
					</label>
					<Input
						style={{ width: "85%" }}
						className={styles.inputItem}
						placeholder='请输入标准问'
						value={standardQuestion}
						maxLength={100}
						onChange={this.onChangeStandard}
					/>
					<div style={{ padding: "10px 0 0 56px" }}>
						{slots.map((slotItem, index) => {
							return (
								<Button
									key={index}
									htmlType='button'
									size='small'
									style={{ marginRight: 10 }}
									onClick={() => this.addSlotsToStandard(slotItem.name)}>
									&lt;{slotItem.name}&gt;
								</Button>
							);
						})}
					</div>
				</div>
        {
          UserSession.isSystemKnowledge() ? '' :
          <div style={{ padding: "5px 0px 5px 10px", width: "100%" }}>
            <label>相似问：</label>
            <Input
              style={{ width: "85%" }}
              placeholder='请输入相似问题, 点击回车继续添加'
              className={styles.inputItem}
              value={this.state.addValue}
              onChange={(event) => {
                this.onChange(event, "a", -1);
              }}
              onPressEnter={this.addValue}
              maxLength={100}
              onFocus={(e) => this.changeQuestionsIndex(-1)}
              ref={`resemblance-1`}
            />
            <span>
              <Icon
                type='plus-circle'
                style={{
                  fontSize: 20,
                  marginLeft: 10,
                  cursor: "pointer",
                  marginTop: 5,
                }}
                onClick={this.addValue}
              />
            </span>
            <div style={{ padding: "10px 0 0 56px" }}>
              {slots.map((slotItem, index) => {
                return (
                  <Button
                    key={index}
                    htmlType='button'
                    size='small'
                    style={{ marginRight: 10 }}
                    onClick={() => this.addSlots(slotItem.name, -1)}>
                    &lt;{slotItem.name}&gt;
                  </Button>
                );
              })}
            </div>
          </div>
        }
				
        {
          UserSession.isSystemKnowledge() ? '' :
          questions.map((q, i) => {
            if ((i > minIndex || i === minIndex) && i < maxIndex) {
              return (
                <div
                  style={{ width: "100%", padding: "15px 0px 5px 66px" }}
                  key={i}>
                  <div>
                    <Input
                      style={{ width: "85%" }}
                      className={styles.inputItem}
                      value={q}
                      onChange={(event) => {
                        this.onChange(event, "b", i);
                      }}
                      onFocus={(e) => this.changeQuestionsIndex(i)}
                      ref={`resemblance${i}`}
                    />
                    <span>
                      <Icon
                        className='dynamic-delete-button'
                        type='close-circle'
                        style={{
                          fontSize: 20,
                          marginLeft: 10,
                          cursor: "pointer",
                          marginTop: 5,
                        }}
                        onClick={() => this.changeQuestions(q, i, "del")}
                      />
                      <Icon
                        type='arrow-up'
                        style={{
                          fontSize: 20,
                          marginLeft: 10,
                          cursor: "pointer",
                          marginTop: 5,
                        }}
                        onClick={() => this.changeQuestions(q, i, "up")}
                      />
                    </span>
                    <div>
                      {this.state.questionIndex === i
                        ? slots.map((slotItem, index) => {
                            return (
                              <Button
                                key={index}
                                htmlType='button'
                                size='small'
                                style={{ marginRight: 10 }}
                                onClick={() => this.addSlots(slotItem.name, i)}>
                                &lt;{slotItem.name}&gt;
                              </Button>
                            );
                          })
                        : null}
                    </div>
                  </div>
                </div>
              );
            }
          })
        }
        {
          UserSession.isSystemKnowledge() ? '' :
          questions.length > 10 ? (
            <div style={{ width: "100%", textAlign: "center" }}>
              <Pagination
                total={questions.length}
                current={page}
                size={10}
                onChange={this.onChangeQuestionPage}
              />
            </div>
          ) : (
            ""
          )
        }
				<div style={{ marginLeft: "10px" }}>
					<Button type='primary' onClick={this.save} disabled={UserSession.isSystemKnowledge()}>
						保存
					</Button>
				</div>
			</div>
		);
	}
}

export default DialogStart;
